#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: mysql ddl to yaml
# 实现菜单解析

# import sys

import pymysql

from com.generator.settings import db_host, db_user, db_password, db_port, db_database, db_charset, getEnvVar
from com.generator.fields import FormatField
from com.generator.meta import Meta
from com.generator.utils import snake_to_camel_case, getTableName, write_file

# reload(sys)
import importlib, sys

importlib.reload(sys)

# sys.setdefaultencoding('utf8')


class FormatTable:
    def __init__(self):
        self.db = pymysql.connect(host=getEnvVar(db_host),
                                  user=getEnvVar(db_user),
                                  password=getEnvVar(db_password),
                                  port=getEnvVar(db_port),
                                  database=getEnvVar(db_database),
                                  charset=db_charset)

        self.cursor = self.db.cursor()
        #  and table_name in ('t_model_sort','t_import_status')
        self.sql = """
        SELECT table_name,replace(table_comment,' ','') FROM information_schema.TABLES where table_schema='foxmind'
        """

    def genTables(self):
        try:
            # 执行SQL语句
            self.cursor.execute(self.sql)
            # 获取所有记录列表
            results = self.cursor.fetchall()
            for rows in results:
                table_name = snake_to_camel_case(getTableName(rows[0]))
                table_comment = rows[1]
                # print("camel_table_name:%s" % table_name)
                # print("table_comment:%s" % table_comment)
                # print("table_name:%s" % rows[0])
                ff = FormatField(rows[0])
                ff.genFields()
                # print(ff.Fields)
                mt = Meta(name=table_name, comment=table_comment, fields=ff.Fields)
                write_file(table_name, mt)

        except Exception as e:
            # tgDb.rollback()
            print("Error: unable to fecth data:" + str(e))

        self.cursor.close()
        self.db.close()


if __name__ == '__main__':
    ft = FormatTable()
    ft.genTables()
